<?php

namespace App\Http\Controllers\API;

use App\Criteria\UserParkCriteria;
use App\Http\Requests\API\CreatePlatformMsgAPIRequest;
use App\Http\Requests\API\UpdatePlatformMsgAPIRequest;
use App\Models\Msgs;
use App\Models\PlatformMsg;
use App\Repositories\PlatformMsgRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
use App\Services\MsgServices;
use DB;

/**
 * Class PlatformMsgController
 * @package App\Http\Controllers\API
 */

class PlatformMsgAPIController extends AppBaseController
{
    /** @var  PlatformMsgRepository */
    private $platformMsgRepository;
    private $status = [0=>'下发中',1=>'下发成功',2=>'下发失败'];
    private $type = [1=>'完整时段',2=>'周期时段'];
    use MsgServices;
    private $park_arr = [];

    public function __construct(PlatformMsgRepository $platformMsgRepo)
    {
        $this->platformMsgRepository = $platformMsgRepo;
        $park_arr = $this->getUserParks();
        $park_arr = $this->getParkCodes($park_arr);
        $this->park_arr = $park_arr;
    }

    /**
     * Display a listing of the PlatformMsg.
     * GET|HEAD /platformMsgs
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->platformMsgRepository->pushCriteria(new RequestCriteria($request));
        $this->platformMsgRepository->pushCriteria(new LimitOffsetCriteria($request));
        $this->platformMsgRepository->pushCriteria(UserParkCriteria::class);
        $platformMsgs = $this->platformMsgRepository->orderBy("id",'desc')->paginate($request->limit);
        foreach ($platformMsgs as $val) {
            $val->type_name = isset($this->type[$val->type])?$this->type[$val->type]:'';
            $val->status_name = isset($this->status[$val->status])?$this->status[$val->status]:'';
        }
        return $this->sendResponse($platformMsgs->toArray(), '获取成功');
    }


    /**
     * Display a listing of the PlatformMsg.
     * GET|HEAD /platformMsgs
     *
     * @param Request $request
     * @return Response
     */
    public function msgs(Request $request)
    {
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;
        $type = $request->input("type",1);
        $mtype = $request->input("mtype");
        $ms = Msgs::where("type",$type);
        if(is_numeric($mtype)){
            $ms = $ms->where("mtype",$mtype);
        }
        $ms = $ms->orderBy("created_at", 'desc')->paginate($pages, array("*"), "page", $page);
        return $this->sendResponse($ms->toArray(), '获取成功');
    }

    /**
     *  delete msg
     *
     */
    public function msgsDelete(Request $request)
    {
        $id = $request->input("id");
        $ms = Msgs::whereIn("id",$id)->delete();
        return $this->sendResponse([], '操作成功');
    }

    /**
     *  update msg
     *
     */
    public function msgsUpdate(Request $request)
    {
        $id = $request->input("id");
        $ms = Msgs::whereIn("id",$id)->update(["type"=>2]);
        return $this->sendResponse([], '操作成功');
    }

    /**
     *  弹框消息
     *
     */
    public function msgsFlag(Request $request)
    {
        $id = $request->input("id");
        $mtype = $request->input("mtype",1);
        $ms = Msgs::whereIn("id",$id)->update(["mtype"=>$mtype]);
        return $this->sendResponse([], '操作成功');
    }

    /**
     * Store a newly created PlatformMsg in storage.
     * POST /platformMsgs
     *
     * @param CreatePlatformMsgAPIRequest $request
     *
     * @return Response
     */
    public function store(CreatePlatformMsgAPIRequest $request)
    {
        $input = $request->all();
        if($input['type'] == 2) {
            $repeat_res = $this->platformMsgRepository->findWhere([
                'park_code' => $input['park_code'],
                'type' => 2,
                'period' => $input['period'],
            ])->first();
            if($repeat_res){
                return $this->sendError('已经存在此周期时段的消息，请检查');
            }
        }
        if($input['type'] == 1) {
            $start_res = $this->platformMsgRepository->findWhere([
                'park_code' => $input['park_code'],
                'type' => 1,
                ['start_time','<=',$input['start_time']],
                ['end_time','>=',$input['start_time']]
            ])->first();
            if($start_res){
                return $this->sendError('下发消息有时间重叠，请检查');
            }
            $end_res = $this->platformMsgRepository->findWhere([
                'park_code' => $input['park_code'],
                'type' => 1,
                ['start_time','<=',$input['end_time']],
                ['end_time','>=',$input['end_time']]
            ])->first();
            if($end_res){
                return $this->sendError('下发消息有时间重叠，请检查');
            }
        }
        $platformMsgs = $this->platformMsgRepository->create($input);
        if($platformMsgs){
            $data = [
                'park_code'=>$platformMsgs->park_code,
                'record_id'=>$platformMsgs->id,
                'msgno'=>$platformMsgs->id,
                'msg'=>$platformMsgs->message,
                'mode'=>1,
            ];
            if($input['type'] == 1){
                $data['start_time'] = strtotime($platformMsgs->start_time);
                $data['end_time'] = strtotime($platformMsgs->end_time);
                $res = $this->sendMsg($data);
            } else if($input['type'] == 2){
                $data ['period'] = $platformMsgs->period;
                $res = $this->issuePeriodMsg($data);
            }
            if($res['code'] == 0){
                $this->platformMsgRepository->update(['status'=>1], $platformMsgs->id);
                return $this->sendResponse($platformMsgs->toArray(), '下发成功');
            } else {
                $this->platformMsgRepository->update(['status'=>2], $platformMsgs->id);
            }
        }

        return $this->sendResponse($platformMsgs->toArray(), '操作成功');
    }

    /**
     * Display the specified PlatformMsg.
     * GET|HEAD /platformMsgs/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var PlatformMsg $platformMsg */
        $platformMsg = $this->platformMsgRepository->findWithoutFail($id);

        if (empty($platformMsg)) {
            return $this->sendError('数据不存在');
        }

        return $this->sendResponse($platformMsg->toArray(), '获取成功');
    }

    /**
     * Update the specified PlatformMsg in storage.
     * PUT/PATCH /platformMsgs/{id}
     *
     * @param  int $id
     * @param UpdatePlatformMsgAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdatePlatformMsgAPIRequest $request)
    {
        $input = $request->all();
        if($input['type'] == 2) {
            $repeat_res = $this->platformMsgRepository->findWhere([
                'park_code' => $input['park_code'],
                'type' => 2,
                'period' => $input['period'],
                ['id','<>',$id]
            ])->first();
            if($repeat_res){
                return $this->sendError('已经存在此周期时段的消息，请检查');
            }
        }
        if($input['type'] == 1) {
            $start_res = $this->platformMsgRepository->findWhere([
                'park_code' => $input['park_code'],
                'type' => 1,
                ['start_time','<',$input['start_time']],
                ['end_time','>',$input['start_time']],
                ['id','<>',$id]
            ])->first();
            if($start_res){
                return $this->sendError('开始时间有重叠，请检查');
            }
            $end_res = $this->platformMsgRepository->findWhere([
                'park_code' => $input['park_code'],
                'type' => 1,
                ['start_time','<',$input['end_time']],
                ['end_time','>',$input['end_time']],
                ['id','<>',$id]
            ])->first();
            if($end_res){
                return $this->sendError('开始时间有重叠，请检查');
            }
        }
        /** @var PlatformMsg $platformMsg */
        $platformMsg = $this->platformMsgRepository->findWithoutFail($id);

        if (empty($platformMsg)) {
            return $this->sendError('数据不存在');
        }
        $platformMsg = $this->platformMsgRepository->update($input, $id);
        if($platformMsg){
            $data = [
                'park_code'=>$platformMsg->park_code,
                'record_id'=>$platformMsg->id,
                'msgno'=>$platformMsg->id,
                'msg'=>$platformMsg->message,
                'mode'=>1,
            ];

            if($input['type'] == 1){
                $data['start_time'] = strtotime($platformMsg->start_time);
                $data['end_time'] = strtotime($platformMsg->end_time);
                $res = $this->editMsg($data);
            } else if($input['type'] == 2){
                $data ['period'] = $platformMsg->period;
                $res = $this->issuePeriodMsg($data);
            }
            if($res['code'] == 0){
                $this->platformMsgRepository->update(['status'=>1], $platformMsg->id);
                $platformMsg->status=1;
                return $this->sendResponse($platformMsg->toArray(), '下发成功');
            } else {
                $this->platformMsgRepository->update(['status'=>2], $platformMsg->id);
                $platformMsg->status=2;
            }
        }

        return $this->sendResponse($platformMsg->toArray(), '操作成功');
    }

    /**
     * Remove the specified PlatformMsg from storage.
     * DELETE /platformMsgs/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var PlatformMsg $platformMsg */
        $platformMsg = $this->platformMsgRepository->findWithoutFail($id);

        if (empty($platformMsg)) {
            return $this->sendError('数据不存在');
        }
        $data = [
            'park_code'=>$platformMsg->park_code,
            'record_id'=>$platformMsg->id,
            'msgno'=>$platformMsg->id,
        ];
        $res = $this->deleteMsg($data);
        if ($res['code'] == 0) {
            $r = $this->platformMsgRepository->delete($id);
            return $this->sendResponse([], '删除成功');
        } else {
            return $this->sendError('删除失败');
        }
    }
}
